package com.steam.xbcc.service.impl;

import com.steam.xbcc.config.HighlightResultMapper;
import com.steam.xbcc.doc.CourseDoc;
import com.steam.xbcc.dto.CourseEsDto;
import com.steam.xbcc.repository.CourseEsRepository;
import com.steam.xbcc.result.EsAggrPageList;
import com.steam.xbcc.result.PageList;
import com.steam.xbcc.service.ICourseEsService;
import com.steam.xbcc.vo.AggrTermsBucketVo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CourseEsServiceImpl implements ICourseEsService {

    @Autowired
    private CourseEsRepository courseEsRepository;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void save(CourseDoc courseDoc) {
        courseEsRepository.save(courseDoc);
    }

    @Override
    public PageList<CourseDoc> search(CourseEsDto courseEsDto) {
        String keyword = courseEsDto.getKeyword();
        Long courseTypeId = courseEsDto.getCourseTypeId();
        String chargeName = courseEsDto.getChargeName();
        String gradeName = courseEsDto.getGradeName();
        Double priceMax = courseEsDto.getPriceMax();
        Double priceMin = courseEsDto.getPriceMin();
        String sortField = courseEsDto.getSortField();
        String sortType = courseEsDto.getSortType();

        HighlightResultMapper highlightResultMapper = new HighlightResultMapper();

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (!StringUtils.isEmpty(keyword)){
            boolQuery.must(QueryBuilders.matchQuery("name", keyword));
        }

        if (courseTypeId != null){
            boolQuery.filter(QueryBuilders.termQuery("courseTypeId", courseTypeId));
        }

        if (!StringUtils.isEmpty(chargeName)){
            boolQuery.filter(QueryBuilders.termQuery("charge", chargeName));
        }

        if (!StringUtils.isEmpty(gradeName)){
            boolQuery.filter(QueryBuilders.termQuery("gradeName", gradeName));
        }

        if (priceMax != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(priceMax));
        }

        if (priceMin != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(priceMin));
        }

        if (!StringUtils.isEmpty(sortField) && !StringUtils.isEmpty(sortType)){
            SortOrder sortOrder = "asc".equalsIgnoreCase(sortType)?SortOrder.ASC:SortOrder.DESC;
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(sortField).order(sortOrder));
        }

        nativeSearchQueryBuilder.withQuery(boolQuery);

        nativeSearchQueryBuilder.withPageable(PageRequest.of(courseEsDto.getPage() -1, courseEsDto.getRows()));

        nativeSearchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("name").preTags("<span style='color:red'>").postTags("</span>"));

        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("gradeNameTermsAgg").field("gradeName"));
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("chargeNameTermsAgg").field("charge"));

        NativeSearchQuery build = nativeSearchQueryBuilder.build();

        // Page<CourseDoc> page = courseEsRepository.search(build);
        AggregatedPage<CourseDoc> courseDocs = elasticsearchRestTemplate.queryForPage(build, CourseDoc.class, highlightResultMapper);

        Aggregations aggregations = courseDocs.getAggregations();

        Map<String, List<AggrTermsBucketVo>> aggrsMap = new HashMap<>();

        aggregations.asMap().entrySet().forEach(e->{
            List<AggrTermsBucketVo> aggrTermsBucketVos = new ArrayList<>();
            String key = e.getKey();
            ParsedStringTerms parsedStringTerms = (ParsedStringTerms) e.getValue();
            parsedStringTerms.getBuckets().forEach(p->{
                AggrTermsBucketVo aggrTermsBucketVo = new AggrTermsBucketVo();
                String keyAsString = p.getKeyAsString();
                long docCount = p.getDocCount();
                aggrTermsBucketVo.setKey(keyAsString);
                aggrTermsBucketVo.setDocCount(docCount);
                aggrTermsBucketVos.add(aggrTermsBucketVo);
            });
            aggrsMap.put(key, aggrTermsBucketVos);
        });

        //return new PageList<>(courseDocs.getTotalElements(), courseDocs.getContent());
        return new EsAggrPageList<>(courseDocs.getTotalElements(), courseDocs.getContent(), aggrsMap);
    }
}
